package cn.wqb.cloudar.utils;

import org.opencv.core.DMatch;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.features2d.DescriptorMatcher;
import org.opencv.xfeatures2d.SURF;

import java.util.ArrayList;
import java.util.List;

/**
 * 需要System.load('I:/JavaWeb/opencv_java/opencv_java342.dll')
 * 需要依赖I:/JavaWeb/opencv_java/opencv-342.jar
 */

public class ARImageRecognition {

    public static int imageMatch(Mat img1, Mat img2) {
        double hessianThreshold = 400;
        int nOctaves = 4, nOctaveLayers = 3;
        boolean extended = false, upright = false;
        SURF detector = SURF.create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright);
        Mat descriptors1 = new Mat();
        Mat descriptors2 = new Mat();
        detector.detectAndCompute(img1, new Mat(), new MatOfKeyPoint(), descriptors1);
        detector.detectAndCompute(img2, new Mat(), new MatOfKeyPoint(), descriptors2);

        DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
        List<MatOfDMatch> knnMatches = new ArrayList<>();
        matcher.knnMatch(descriptors1, descriptors2, knnMatches, 2);

        float ratioThresh = 0.7f;
        List<DMatch> listOfGoodMatches = new ArrayList<>();
        for (int i = 0; i < knnMatches.size(); i++) {
            if (knnMatches.get(i).rows() > 1) {
                DMatch[] matches = knnMatches.get(i).toArray();
                if (matches[0].distance < ratioThresh * matches[1].distance) {
                    listOfGoodMatches.add(matches[0]);
                }
            }
        }
        int count = listOfGoodMatches.size();
        System.out.println("========匹配数：" + count);
        return count;
    }

}
